﻿document.write("<script language='javascript' src='/resources/js/views/defineTable.js'></script>");
document.write("<script language='javascript' src='/resources/js/printUtils.js'></script>");

var editIndex = undefined;
var formsDepartId = 0;					//部门编号
var reportStatus = 0;					//上报状态
var reportDate=0;   			 		//报出日期 
var reportPerson=0;         			//填表人 
// var isAudit_cli=false;    				//是否触发审核（都需要审核）
var auditPass=false;    				//审核是否通过
var total=0;							//数据总条数
// var isNotTsData=false;                  //是否暂存数据（都不需要暂存）

// 上报状态查询 0:删除(默认),1:未上报;2:上报中(部分上报);3:审核(自己审核);4:审核(上级部门);5:审核通过(不允许修改);
var NO_CHANGE = 0;   			    	//数据已删除或者没有上报数据
var CHANGE = 5;							//审核已通过不允许修改
var UN_PASS = 4;
var page = 1;
var pageSize = 200;
// var isEdit=false;
var departId='';
var skipCode= "[A004,A031,A032,A033,A034,A035,A036,A037,A038,A042,A046,A051,A055,A059,A063,A067,A071,A075,A079,A083,A087,A091,A095,A099,A111,A112,A113,A118,A122,A126,A130,A134,A138,A142,A146,A150,A154,A158,A162,A166,A170,A174,A187,B004,B010,B024,B028,B034,C028,C032,C036,C040,C044,C048,C052,C056,C060,C064,C068,C072,C076,C080,C084,C088,C092,C096,C100,C104,C108,C112,C116,C120,C124,C128,C132,C136,C140,C144,C148,C152,C156,C160,C164,C168,C172,C176,C180,C184,C188,C192,C196,C200,C204,C208,C212,C216,C220,C224,C228,C232,C236,C240,C244,C248,C252,C256,C260,C264,C268,C272,C276,C280,C284,C288,C292,C296,C300,C304,C308,C312,C316,C320,C324,C328,C332,C336,C340,C344,C348,C352,C356,C360,C364,C368,C375,C379,C383,C387,C391,C395,C399,D004,D008,D012,D016,D020,D024,D028,D032,D036,D040,D044,D048,D052,D056,D060,D064,D068,D072,D076,D080,D084,D088,D092,D096,D100,D104,D108,D112,D116,D120,D124,D128,D132,D136,D140,D144,D148,D152,D156,D160,D164,D168,D172,D176,D180,D184,D188,D192,D196,D200,D204,D208,D212,D216,D220,D224,E004,E008,E012,E016,E020,E027,E031,E035,E039,E044,E048,E052,F004,F008,F012,F016,F020,F024,F028,F032,F036,F040,F044,F048,F052,F056,F060,F064,F068,F072,F076,F080,F084,F088,F092,F096,F100,F104,F108,F112,F116,F120,F124,F128,G004,G008,G012,G016,G020,G024,G028,G032,G036,G040,G044,G048,G052,G056,G060,G064,G068,H007,H011,H039,H043,I004,I008,I012,I016,I020,I024,I028,I032,I036,I040,I044,I048,I052,I056,I060,I064,I068,I072,I076,I080,I084,I088,I092,I096,I100,I104,I108,I112,I116,I120,I124,I128,I132,I136,I140,I144,J007,J011,J015,J019,J023,J027,J031,J035,J039,J043,J047,J051,J055,J059]";

//接口地址
var actionGetSelfList='/report/self/list.do';     		//查询上报状态(获得上报时间，上报人，上报状态)
var myDepart='/department/myDepart.do';   			//获取单位负责人，统计负责人，联系电话 的接口
var getStatus='/report/status/now.do';  	    		//上报状态查询(接口地址已变更)
var finish='/report/status/finish.do';       	    	//更新上报状态为已完成接口(接口地址已变更)
var getAudit_14_5='/resources/js/views/auditFoumal_14_5.do'		//获得审核关系公式
var getReport='/forms/list.do';    					//获得报表信息接口 // TODO 改成 报表/领域
var saveAll ='/report/save/all.do';                 //多条数据上报

var datas=[];
var isEnd=false;
// var dialogAuditDiv=false;	审核错误数据提示

//通过上报状态控制相应的操作
function judgeStatus(formsDepartId){
	 var yearSelect =  $("#yearSelect").combobox("getValue");
	 var formid=$("#formid").combobox('getValue');   //报表（妇儿、社会）
	 $.get(getStatus,{"depart":formsDepartId,"year":yearSelect,"formsid":formid},function(data){
			if(data.code==200){
			 	data=data['data'];
			 	reportStatus=data.status;
			 	var time = new Date();
			 	reportDate = time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate();
			 	reportPerson=data.editor;
			 	
			 	//显示上报时间以及 填表人
			 	if(reportDate!=null&&reportDate!=undefined){
		    		$('.reportDate').text(reportDate);
					$("#print_date").val(reportDate)
		    	}
                $("#maker").val(data.maker);

		    	// isEdit=false;
		    	if(isEnd){
		    		//endEdit();
		    	}
			 	//再查询指标信息
			 	query(page, pageSize)
			} else{ //否则直接显示当前上报时间
				cleartable(); 
				$('.reportDate').text(new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate());
			}
	 }, "json");
}

//根据年份，分页查询指标信息
function query(curPage, pageSize) {

	curPage = parseInt(curPage);
	pageSize = parseInt(pageSize);
	var yearSelect =  $("#yearSelect").combobox("getValue");
	if(yearSelect==null){
		yearSelect = formatDate(new Date(), "yyyy");
	}
	var yearLast =  yearSelect-1;
	var formid=$("#formid").combobox('getValue');   //报表（妇儿、社会）
	var indicatorTypeIds = $('#indicatorTypeSelect').combobox('getValues')+"";

	var showReportColumnsvalue = {
		yearSelect: {field:yearSelect,title:yearSelect+"",width:200,align:'center',
			editor: {type:'text'}, //new
			formatter: function (value, row, index) {

				var valueSelect=getValueFromString(row[yearSelect]);
				var reportType = getRtypeFromString(row.rtype);
				// value 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注

				return getShowValue(reportType, valueSelect);
			}
		},
		yearLast: {field:yearLast+"",title:yearLast+"",width:200,align:'center',
			formatter: function (value, row, index) {
				if(isEmpty(row.iname)){
					return '';
				}
				if(isEmpty(value)){
					return 0;
				}
				return getValueFromString(value);
			}
		},
		rtype: {field:"rtype",title:'数据类型',width:80,
			formatter: function (value, row, index) {
				if(value==null||value==0){
					return pipingLevel[0].text;
				}
				for(var i =0;i<pipingLevel.length;i++){
					if(pipingLevel[i].value==value){
						return pipingLevel[i].text;
					}
				}
				return "未知";
			},
			editor:{
				type:"combobox",
				options: {
					data:pipingLevel,
					valueField: "value",
					textField: "text",
					editable: true
				}
			}
		}

	}
	var reportShowColumns = [
 		defineTableReportAllColumns["iname"],
 		defineTableReportAllColumns["code"],
 		defineTableReportAllColumns["unit"],
 		defineTableReportAllColumns["places"],
 		showReportColumnsvalue["yearLast"],
 		showReportColumnsvalue["yearSelect"],
 		showReportColumnsvalue["rtype"],
 		defineTableReportAllColumns["sname"],
 		defineTableReportAllColumns["memo"]  //备注
 	];
	$.get(actionGetSelfList, {"year": yearSelect,"formsid":formid, "indicatorTypeIds":indicatorTypeIds, "page": curPage, "pageSize": pageSize}, function (data) {

		if(data.code==200){
			var dataa = data["data"].results;
			var total= data["data"].size;	  //total
			var totalPage = Math.ceil(total / pageSize);
			var start = (curPage-1) * pageSize;
			if(dataa==null || dataa==undefined || dataa=='[]' || dataa==[] || dataa==''){
				cleartable();
				return;
			}
			datas=dataa;
            var dataLength=datas.length;
	        var iHeight = document.documentElement.clientHeight;
            $('#tt').datagrid({
            	toolbar:CreateToolBar(true,true,true,true,true, true,true),
            	iconCls : 'icon-edit',
                width : '99%',
                height:iHeight-185+'px',
                columns: [reportShowColumns],
                rownumbers: false,
                pagination: false,//打开翻页功能
                sortable:true,
                sortName:"code",//排序
                multiSort:true, //定义是否允许多列排序
    			remoteSort:false,//表示前端排序不请求服务器
    			sortOrder:'asc',
                pageNumber: curPage,//显示数据列用
                pageSize: pageSize,
                pageList: [200,500,1000],
                data:datas,
                // onBeforeEdit : function(index, row) {
                //     if(row["rtype"]==null){
                //         row["rtype"]=1;
                //     }
                // },
				// onAfterEdit : function(index, row) {
				// 	if(isNotTsData){
				// 		return;
				// 	}
				// },
                onLoadSuccess:function(data){
                    isEnd=true;
                    if(reportStatus!=NO_CHANGE){
                    	// TODO 先临时注销
                        // CRUD.Audit(false);
                    }
                }
            })

            $("#pp").pagination({
                total: total,
                pageList: [200,500,1000],
                pageSize: pageSize,
                pageNumber: curPage,
                beforePageText: '第',
                afterPageText: '页    共 ' + totalPage + ' 页',
                displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
                onSelectPage: function (curPage, pageSize) {
                	query(curPage, pageSize);
                },
                onChangePageSize: function (ps) {
                    pageSize = ps;
                }
            });
            // if(isEdit){
            // 	CRUD.Update();
            // 	$('#tt').datagrid('selectRow', 0);
            // }
		}
		// else{
		// 	cleartable();
		// }
		
	}, "json");
}

//清除表格信息
function cleartable(){
	$('#tt').datagrid({data:[]});
	$("#pp").pagination({
        beforePageText: '第',
        afterPageText: '页    共 ' + 0 + ' 页',
        displayMsg: '当前显示 ' + 0 + '-' + 0 + ' 条记录 共 ' + 0 + ' 条记录',
    });
};

$(document).ready(function () {

    $("#yearSelect").combobox("setValue", getHalfYear());

    //查询本部门信息并通过上报状态判断是否 查询指标信息
    CRUD.setSelfDepartInfo();
    InitForm();
	loadForm();
});

function getHalfYear(){
	var nowDate = new Date();
	var nowYear = formatDate(nowDate, "yyyy");
	var nowMonth = nowDate.getMonth()+1;
	var yearValue = nowYear-2;
	if(nowMonth>=10 && nowMonth<=12){
		yearValue =  nowYear-1;
	}
	return yearValue;
}

//批量提交
function submitSaveAll(params){
	$.ajax({ 
        type : "post", 
        url : saveAll, 
        data : params, 
        async : false, 
        success : function(data){ 
        	data = eval("(" + data + ")"); 
        	if(data.code!=200){
        		$("#dialogSubmitDiv").dialog('close');
        		alert("数值报错,请重新填写!");
        		return false;
  			}
        } 
    });
	query(page, pageSize);
    return true;
}

var CRUD = {
    queryList: function () {
    	query(page, pageSize);
    },
    Add: function () {
        var data=$('#tt').datagrid('getData');
        for(var i=0; i < data.rows.length; i++){
            saverow(i);
        }
    },
    //上报数据
    Save:function(){
    	$('#tt').datagrid('acceptChanges');
    	if(auditPass==false){
        	$.messager.alert('系统提示', '请先审核数据!','warning'); 
        	return;
        }
        var reportPerson=$("#maker").val();
        if(reportPerson==null||reportPerson==""){
        	$.messager.alert('系统提示', '请先填入填表人姓名!','warning');
        	return;
        }
        var noPass =[];
		var arrtable = [];
		var iTr=[];
		var iTable = document.getElementsByTagName("table");
		for (var j = 0; j < iTable.length; j++) {
			if (iTable[j].className == "datagrid-btable") {
				arrtable.push(iTable[j]);
			}
		}
		for (var i = 0; i < arrtable.length; i++) {
			if(arrtable[i].childNodes[0].childNodes.length>0){
				 iTr = arrtable[i].getElementsByTagName("tr");
			}
		}
		for(var z=0; z<iTr.length;z++){
			if(iTr[z].childNodes[5].style.background == "red"){
				noPass.push(iTr[z].childNodes[5]);
			}
		}
		// 审核是否通过
		if(noPass.length>0){
			$.messager.alert('系统提示','数据未通过审核!暂时无法上报！！','warning')
			return;
		}

		// 保存数据
		submitSaveAllStatus = saveAllData(formsDepartId);

		//全部提交成功后，才会更新状态。
		if(submitSaveAllStatus){
			var formid=$("#formid").combobox("getValue");
			var makerName=$("#maker").val();
			var yearSelect =  $("#yearSelect").combobox("getValue");
			var params= {"year":yearSelect, "depart": formsDepartId,"formsid":formid,"maker":makerName};
			$.ajax({
				type : "post",
				url : finish,
				data : params,
				async : false,
				success : function(data){
					data = eval('(' + data + ')');
					$("#dialogSubmitDiv").dialog('close');
					if(!data.success){
						$.messager.alert('系统提示','数据上报错误!','error')
					}else{
						$.messager.alert('系统提示','数据上报完成','info')
						judgeStatus(departId);
					}
				}
			});
		}
    },

	StagingSave : function(){
		// endEdit();
		saveAllData(formsDepartId);
		// isEdit=false;
		cleartable();
		query(page, pageSize);
		return true;
	},

    //查询本部门信息并且根据部门id查询上报状态登信息(judgeStatus(departId))
    setSelfDepartInfo: function () {
    	$.get(myDepart, function (data) {
    		data = eval('(' + data + ')');
    		if (data == null) {
    			$.messager.show({
    				title: '系统提示',
    				msg: '获取用户部门信息失败！',
    				timeout: 1500
    			});
    		} else {
                // editorName=data.name;
                if(data['charge']!=null&&data['charge']!=undefined){
                    $('.charge').text(data['charge']);
                }
                if(data['author']!=null&&data['author']!=undefined){
                    $('.author').text(data['author']);
                }
    			if(data['phone']!=null&&data['phone']!=undefined){
    				$('.phone').text(data['phone']);
    			}
    			if(data['id']!=null&&data['id']!=undefined){
    				departId=data['id'];
    				formsDepartId=data['id'];
    			}
				$("#print_charge").val(data['charge']); // 单位负责人
				$("#print_author").val(data['author']); // 部门统计负责人
				$("#print_phone").val(data['phone']); // 电话
				$("#print_editor").val(data['editor']); // 编辑人员
				$("#print_contact").val(data['contact']); // 联系人

    			judgeStatus(departId);
    		}
    	});
    },

	//编辑数据
	Update: function () {
		var data=$('#tt').datagrid('getData');
		for(var i=0; i < data.rows.length; i++){
			editrows(i);
		}
		//页面初始后才开始初始化复制功能
		comm.datagrid.initExcel2Grid({gid:'tt',inputClass:'datagrid-editable-input'});
	},
    // //暂存
    // Staging: function (){
    // 	//注意用浏览器做缓存存入的数据量是很小的。
    // 	endEdit();
    // },
    //数据关系审核
    Audit: function () {
    	$('#tt').datagrid('acceptChanges');
		doAuditData();
    	// if(dialogAuditDiv){
		// 	$('#dialogAudit').dialog('close');
		// 	dialogAuditDiv=false;
		// }
    },
    //申请退回数据
    Back:function(){
		var yearSelect =  $("#yearSelect").combobox("getValue");
		$("#formsid").val($("#formid").combobox("getValue"));
		$('#dialogAdd').dialog('open');
		$('#depart').val(formsDepartId);
		$('#year').val(yearSelect);
    }
};

function saveAllData(formsDepartId) {

	$('#tt').datagrid('acceptChanges');
	$("#dialogSubmitDiv").dialog('open');
	var yearSelect =  $("#yearSelect").combobox("getValue");
	var formid=$("#formid").combobox('getValue');   //报表（妇儿、社会）
	var editorNames=$("#maker").val();

	// var rows = $("#tt").datagrid("getChanges");
	var rows = $("#tt").datagrid("getRows");
	if(rows==null||rows.length<1){
		return;
	}

	var values="";
	var params={
		'year':yearSelect,
		'formsid':formid,
		'departid':formsDepartId,
		'editor':editorNames,
		'values':values
	}

	var step=50;
	var countValues=0;
	var submitSaveAllStatus=false;

	for(var i=0; i<rows.length; i++){
		// 跳过无需手填的指标
		if(skipCode.includes(rows[i].code)){
			continue;
		}
		var valueSelect=getValueFromString(rows[i][yearSelect]);
		var rtype = getRtypeFromString(rows[i].rtype);
		var reportValue = getReportValue(rtype, valueSelect);
		var rowsBase=rows[i].remark==null||typeof rows[i].remark==undefined||rows[i].remark==""?"":rows[i].remark;

		values+=rows[i].id+","+rtype+","+reportValue+","+rowsBase+";";
		countValues++;

		if(countValues>=step){ // 条数够了，则上报一次
			params.values=values;
			if(!submitSaveAll(params)){
				submitSaveAllStatus=false;
				break;
			}else{
				submitSaveAllStatus=true;
			}
			values="";
			countValues=0;
		}
	}
	// 还存在未上报的数据，最后再上报一次
	if(countValues>0){
		params.values=values;
		if(!submitSaveAll(params)){
			submitSaveAllStatus=false;
		}else{
			submitSaveAllStatus=true;
		}
	}
	return submitSaveAllStatus;
}

function editrows(index) {
	$('#tt').datagrid('beginEdit', index);
}

function doAuditData() {

	var s_target_=[];    //未通过审核的指标数组
	var s_formula=[];
	var auditHint=[];
	var yearSelect =  $("#yearSelect").combobox("getValue");
	$.get(getAudit_14_5, function (json) {
		var needAuditCode =[];
		var auditData=json;  //获得审核公式
		var data=$('#tt').datagrid('getRows');    //获取表格所有行
		for (var i = 0; i < auditData.length; i++) {
			needAuditCode[i]=auditData[i]["code"];
			for (var j = 0; j < data.length; j++) {
				if(data[j].code==auditData[i].code){
					data[j]["auditFormulas"]=auditData[i]["auditFormulas"];

				}
			}
		}
		//------------------------获得不合格的指标代码数组START
		for (var i = 0; i < data.length; i++) {

			// 跳过无需验证的指标
			if(skipCode.includes(data[i].code)){
				continue;
			}

			var auditFormulas=data[i].auditFormulas; //审核关系公式

			// 获取当前应有的数值
			var tempValue = data[i][yearSelect];
			var rtype = data[i].rtype;

			if(rtype==4
				&& !isContains(tempValue, ":")
				&& !isContains(tempValue, "：")){
				var hour=parseInt(tempValue / 60);
				var minute=tempValue % 60;
				tempValue = hour+":"+minute;
			}

			if(!checkValue(rtype, tempValue)){
				var rtypeStr = "";
				if(rtype==2){
					rtypeStr ="[空格],";
				}
				if(rtype==3){
					rtypeStr ="[暂无数据],";
				}
				if(rtype==5){
					rtypeStr ="[市级免报],";
				}
				if(rtype==6){
					rtypeStr ="[县级免报],";
				}
				$.messager.alert('错误', '编码:['+data[i]["code"]+'],'+rtypeStr+'数值['+tempValue+']不正确,请重填!','error');
				// if(dialogAuditDiv){
				// 	$('#dialogAudit').dialog('close');
				// 	dialogAuditDiv=false;
				// }
				return;
			}

			var needAuditCodeFlag = false;
			for (var j = 0; j < needAuditCode.length; j++) {
				if(needAuditCode[j]==data[i].code){
					needAuditCodeFlag = true;
					break;
				}
			}
			if(!needAuditCodeFlag){
				continue;
			}

			if(auditFormulas==null||auditFormulas==undefined){
				continue;
			}
			if(auditFormulas.indexOf("_")!=-1){
				var array=auditFormulas.split("_");
				if(array.length!=2){
					continue;
				}
				switch(array[1]){
					case ">>>+":
						// {"code":"A001","auditFormulas":"A001>A002&A001>A003&A001≥A002+A003_>>>+"}
						// 	array[0] = A001>A002&A001>A003&A001≥A002+A003
						var array1=array[0].split("&")[0];  //array1=A001>A002
						var array2=array[0].split("&")[1];  //array2=A001>A003
						var array3=array[0].split("&")[2];  //array3=A001≥A002+A003

						var selfCode=array1.split(">")[0];  //本指标代码 A001
						var ratioCode1=array1.split(">")[1];  //本指标代码 A002
						var ratioCode2=array2.split(">")[1];  //本指标代码 A003
						var ratioCode3=array3.split("≥")[1];  //本指标代码 A002+A003

						var isTrun1= getValues(selfCode,ratioCode1);  //代码对应的数值 A001.value,A002.value
						var isTrun2= getValues(selfCode,ratioCode2);  //代码对应的数值 A001.value,A003.value
						var values1=isTrun1.split(","); // values1[A001.value,A002.value]
						var values2=isTrun2.split(","); // values2[A001.value,A003.value]

						//A002 和 A003 都没有值
						if((null==values1[1]||""==values1[1]||0==values1[1]) && (null==values2[1]||values2[1]==""||0==values2[1])) {
							break;
						}
						// 异常情况
						// values1[0] A001.value <=  values1[1] A002.value
						// values2[0] A001.value <=  values2[1] A003.value
						// values1[0] A001.value <  values1[1] A003.value +  values2[1] A003.value
						if(parseFloat(parseFloat(values1[0]).toFixed(2))<=parseFloat(parseFloat(values1[1]).toFixed(2))
							||parseFloat(parseFloat(values2[0]).toFixed(2))<=parseFloat(parseFloat(values2[1]).toFixed(2))
							||parseFloat(parseFloat(values1[0]).toFixed(2))<(parseFloat((parseFloat(values1[1])+parseFloat(values2[1])).toFixed(2)))){
							s_target_.push(selfCode);
							s_formula.push(array[0]);
							auditHint.push({'code':selfCode,'relation':array[0]});
						}
						break;

					case "≥≥≥+":
						// {"code":"A001","auditFormulas":"A001≥A002&A001≥A003&A001≥A002+A003_≥≥≥+"}
						// 	array[0] = A001≥A002&A001≥A003&A001≥A002+A003
						var array1=array[0].split("&")[0];  //array1=A001≥A002
						var array2=array[0].split("&")[1];  //array2=A001≥A003
						var array3=array[0].split("&")[2];  //array3=A001≥A002+A003

						var selfCode=array1.split("≥")[0];  //本指标代码 A001
						var ratioCode1=array1.split("≥")[1];  //本指标代码 A002
						var ratioCode2=array2.split("≥")[1];  //本指标代码 A003
						var ratioCode3=array3.split("≥")[1];  //本指标代码 A002+A003

						var isTrun1= getValues(selfCode,ratioCode1);  //代码对应的数值 A001.value,A002.value
						var isTrun2= getValues(selfCode,ratioCode2);  //代码对应的数值 A001.value,A003.value
						var values1=isTrun1.split(","); // values1[A001.value,A002.value]
						var values2=isTrun2.split(","); // values2[A001.value,A003.value]

						//A002 和 A003 都没有值
						if((null==values1[1]||""==values1[1]||0==values1[1]) && (null==values2[1]||values2[1]==""||0==values2[1])) {
							break;
						}
						// 异常情况
						// values1[0] A001.value <  values1[1] A002.value
						// values2[0] A001.value <  values2[1] A003.value
						// values1[0] A001.value <  values1[1] A003.value +  values2[1] A003.value
						if(parseFloat(parseFloat(values1[0]).toFixed(2))<parseFloat(parseFloat(values1[1]).toFixed(2))
							||parseFloat(parseFloat(values2[0]).toFixed(2))<parseFloat(parseFloat(values2[1]).toFixed(2))
							||parseFloat(parseFloat(values1[0]).toFixed(2))<(parseFloat((parseFloat(values1[1])+parseFloat(values2[1])).toFixed(2)))){
							s_target_.push(selfCode);
							s_formula.push(array[0]);
							auditHint.push({'code':selfCode,'relation':array[0]});
						}
						break;

					case "≥≥":
						// {"code":"D129","auditFormulas":"D129≥D130&D129≥D131_≥≥"},
						// 	array[0] = D129≥D130&D129≥D131
						var array1=array[0].split("&")[0];  //array1=D129≥D130
						var array2=array[0].split("&")[1];  //array2=D129≥D131

						var selfCode=array1.split("≥")[0];  //本指标代码 D129
						var ratioCode1=array1.split("≥")[1];  //本指标代码 D130
						var ratioCode2=array2.split("≥")[1];  //本指标代码 D131

						var isTrun1= getValues(selfCode,ratioCode1);  //代码对应的数值 D129.value,D130.value
						var isTrun2= getValues(selfCode,ratioCode2);  //代码对应的数值 D129.value,D131.value
						var values1=isTrun1.split(","); // values1[D129.value,D130.value]
						var values2=isTrun2.split(","); // values2[D129.value,D131.value]

						//D130 和 D131 都没有值,肯定能过
						if((null==values1[1]||""==values1[1]||0==values1[1]) && (null==values2[1]||values2[1]==""||0==values2[1])) {
							break;
						}
						// 异常情况
						// values1[0] D130.value <  values1[1] D130.value
						// values2[0] D130.value <  values2[1] D131.value
						if(parseFloat(parseFloat(values1[0]).toFixed(2))<parseFloat(parseFloat(values1[1]).toFixed(2))
							||parseFloat(parseFloat(values2[0]).toFixed(2))<parseFloat(parseFloat(values2[1]).toFixed(2))){
							s_target_.push(selfCode);
							s_formula.push(array[0]);
							auditHint.push({'code':selfCode,'relation':array[0]});
						}
						break;

					case "≥+":
						// {"code":"D129","auditFormulas":"D129≥D130+D131_≥+"},
						// 	array[0] = D129≥D130+D131
						var selfCode=array[0].split("≥")[0];  //本指标代码 D129
						var array3=array[0].split("≥")[1];  //array3=D130+D131

						var ratioCode1=array3.split("+")[0];  //本指标代码 D130
						var ratioCode2=array3.split("+")[1];  //本指标代码 D131

						var isTrun1= getValues(selfCode,ratioCode1);  //代码对应的数值 D129.value,D130.value
						var isTrun2= getValues(selfCode,ratioCode2);  //代码对应的数值 D129.value,D131.value
						var values1=isTrun1.split(","); // values1[D129.value,D130.value]
						var values2=isTrun2.split(","); // values2[D129.value,D131.value]

						//A002 和 A003 都没有值,无需判断
						if((null==values1[1]||""==values1[1]||0==values1[1]) && (null==values2[1]||values2[1]==""||0==values2[1])) {
							break;
						}
						// 异常情况
						// values1[0] D129.value < (values1[1] D130.value +  values2[1] D131.value)
						if(parseFloat(parseFloat(values1[0]).toFixed(2))
							<(parseFloat((parseFloat(values1[1])+parseFloat(values2[1])).toFixed(2)))){
							s_target_.push(selfCode);
							s_formula.push(array[0]);
							auditHint.push({'code':selfCode,'relation':array[0]});
						}
						break;
					default:
						break;
				}
			}
		}

		var htm="";
		$("#auditHint >tr").remove();
		for(var au=0,len=auditHint.length;au<len;au++){
			htm+="<tr><td>"+auditHint[au].code+"</td><td>"+auditHint[au].relation+"</td></tr>";
		}
		// if(dialogAuditDiv){
		// 	$('#dialogAudit').dialog('close');
		// 	dialogAuditDiv=false;
		// }

		if(auditHint.length>0){
			$("#auditHint").append(htm);
			$("#dialogAudit").dialog('open');
		}else{
			$('#dialogAudit').dialog('close');
			// dialogAuditDiv=false;
		}
		$('#tt').datagrid('acceptChanges');
//		                ------------------------获得不合格的指标代码数组END

//		    	        ------------加背景色START
		var arrtable = [];
		var iTr=[];
		var iTable = document.getElementsByTagName("table");
		for (var j = 0; j < iTable.length; j++) {
			if (iTable[j].className == "datagrid-btable") {
				arrtable.push(iTable[j]);
			}
		}
		for (var i = 0; i < arrtable.length; i++) {
			if(arrtable[i].childNodes[0].childNodes.length>0){
				iTr = arrtable[i].getElementsByTagName("tr");
			}
		}
		for(var z=0; z<iTr.length;z++){
			for (var i = 0; i < s_target_.length; i++) {
				if (iTr[z].childNodes[1].childNodes[0].innerHTML==s_target_[i]) {
					iTr[z].childNodes[5].style.background = "red";
					iTr[z].childNodes[5].childNodes[0].childNodes[0].title="该指标未通过审核，审核关系为："+s_formula[i];
					break;
				} else{
					iTr[z].childNodes[5].style.background = "white";
				}
			}
		}
		if(auditHint.length<1){
			$.messager.alert('系统提示', '已审核通过，请点击上报数据！','info');
			auditPass=true;
		}
	},"JSON");
}

//简单的>,<,>=,<=,=的情况下取得指标数值
function getValues(selfCode,ratioCode){

	var data=$('#tt').datagrid('getRows');
	var yearSelect =  $("#yearSelect").combobox("getValue");
	var selfValue=0;    //本指标代码值
	var ratioValue=0;  //对比的式子(a.只有代码：A08 b.一个式子：A08*1000)
	//本指标代码对应的值
	for (var j = 0; j < data.length; j++) {
		if(data[j].code==selfCode){
			selfValue=getValueFromString(data[j][yearSelect]);
			break;
		}
	}
	//判断比较运算符第二个对比的是指标还是数字
	if(isNaN(ratioCode)){
		for (var j = 0; j < data.length; j++) {
			if(data[j].code==ratioCode){
				ratioValue=getValueFromString(data[j][yearSelect]);
				if(ratioValue=="*"){
					return true;
				}
				break;
			}
		}
	}else{
		ratioValue=ratioCode;  //值等于代码
	}
	return selfValue+","+ratioValue;
}

//创建表头按钮(编辑全部， 暂存数据两按钮)
function CreateToolBar(isUpdate,isStaging,isAdd,isAudit,isBack,isprints,isexportexcel) {
// function CreateToolBar(isUpdate,isStaging,isAdd,isAudit,isBack) {
    var a = [];
    if (isUpdate) {
        a.push({
            text: '【1】录入数据',
            iconCls: 'icon-add',
            handler: function () {
            	if(reportStatus==NO_CHANGE||reportStatus==CHANGE){
            		$.messager.alert('系统提示', '已上报的数据暂时不能录入，如需录入数据请申请修改！','info');
            		return;
            	}
				if(reportStatus==UN_PASS){
					$.messager.alert('系统提示', '数据申请退回还未批准，请联系审核管理员！','info');
					return;
				}
            	// isEdit=true;
            	// isAudit_cli=false;
                CRUD.Update();
            }
        });
        a.push('-');
    }

	if (isStaging) {
		a.push({
			text: '【2】暂存数据',
			iconCls: 'icon-save',
			handler: function () {
				if(reportStatus==5){
					$.messager.alert('系统提示', '已上报的数据无需暂存！','info');
					return;
				}
				if(reportStatus==UN_PASS){
					$.messager.alert('系统提示', '数据申请退回还未批准，请联系审核管理员！','info');
					return;
				}
				if(reportStatus==NO_CHANGE||reportStatus==CHANGE){
					$.messager.alert('系统提示', '数据未作任何修改，无需暂存！','info');
					return;
				}

				// isNotTsData=true;
				CRUD.StagingSave();
			}
		});
		a.push('-');
	}

    if (isAudit) {
        a.push({
            text: '【3】审核数据',
            iconCls: 'icon-search',
            handler: function () {
            	if(reportStatus==NO_CHANGE){
            		$.messager.alert('系统提示', '数据不存在审核无效！！','info');
            		return;
            	}
				if(reportStatus==CHANGE){
					$.messager.alert('系统提示', '已上报的数据，如需审核数据请申请修改！','info');
					return;
				}
				if(reportStatus==UN_PASS){
					$.messager.alert('系统提示', '数据申请退回还未批准，请联系审核管理员！','info');
					return;
				}
              	// isNotTsData=true;
              	// $('#dialogAudit').dialog('open');
              	// dialogAuditDiv=true;
                CRUD.Audit(true);
                // isAudit_cli=true;
                // isEdit=false;
            }
        });
        a.push('-');
    }

    if (isAdd) {
        a.push({
            text: '【4】上报数据',
            iconCls: 'icon-up',
            handler: function () {
            	if(reportStatus==NO_CHANGE||reportStatus==CHANGE){
            		$.messager.alert('系统提示', '已上报的数据不能重复上报！','info');
            		return;
            	}
				if(reportStatus==UN_PASS){
					$.messager.alert('系统提示', '数据申请退回还未批准，请联系审核管理员！','info');
					return;
				}
				// isAudit_cli=true;
            	// isNotTsData=false;
            	// isEdit=false;
                CRUD.Save();
            }
        });
        a.push('-');
    }
    if(isprints){
    	a.push({
            text: '【5】打印报表',
            iconCls: 'icon-print',
            handler: function () {
            	if(reportStatus!=5){
            		$.messager.alert('系统提示', '数据暂未上报，无法打印','info');
            		return;
            	}
				printReports();
            }
        });
        a.push('-');
    }

    if (isBack) {
        a.push({
            text: '申请修改',
            iconCls: 'icon-edit',
            handler: function () {
				if(reportStatus==UN_PASS){
					$.messager.alert('系统提示', '数据申请退回还未批准，请联系审核管理员！','info');
					return;
				}
            	if(reportStatus!=5){
            		$.messager.alert('系统提示', '数据暂未上报，无需申请修改','info');
            		return;
            	}
                CRUD.Back();
            }
        });
        a.push('-');
    }

    if(isexportexcel){
    	a.push({
            text: '导出excel文件',
            iconCls: 'icon-excel',
            handler: function () {
            	exportexcel();
            }
        });
        a.push('-');
    }
    return a;
}

//编辑结束触发事件
function endEdit(){
    var rows = $('#tt').datagrid('getRows');
    for ( var i = 0; i < rows.length; i++) {
        $('#tt').datagrid('endEdit', i);
    }
}

function editrow(index) {
	if(reportStatus==NO_CHANGE||reportStatus==CHANGE){
		return;
	}
    if(editIndex != undefined){
		saverow(editIndex);
    }
    $('#tt').datagrid('beginEdit', index);
    editIndex = index;
}

function saverow(index) {
	$('#tt').datagrid('endEdit', index);
}

//有小数位,最多4位
function isNumber(str){
	if(str==null||str.length<1){
		return false;
	}
    var reg1= "^(-?\\d+)(\\.\\d+)?$";
    var regExp = new RegExp(reg1);
	return regExp.test(str);
}

//申请退回提交事件
function tj(){
	var desc= $('#desc').val();
	if(desc==null||desc.length<1){
		$.messager.alert('系统提示', '请填写，修改的理由!','warning');
		return;
	}
    $('#fmAdd').form('submit', {
		success : function(data) {
			data = eval('(' + data + ')');
			if(data.success){
				 $.messager.alert('系统提示', '提交成功，等待处理...','info');
				 $('#dialogAdd').dialog('close');
			}
		}
	});
}

//从字符串中获取数值  input：1_0.0_60879.0_40_ 返回 60879.0
function getValueFromString(value){

	var result;
	if(value===null||value==null||value==""||value=="null"||value=="NULL"){
		result='';
	}else if(value.indexOf('_')!=-1){
		result = value.split("_")[2];
	}else {
		result = value;
	}

	if(result===null||result==null||result==""||result=="null"||result=="NULL"){
		result='';
	}
	return result;
}

//从字符串中获取类型  input：1_0.0_60879.0_40_ 返回 1
function getRtypeFromString(value){

	var result;
	if(value===null||value==null||value==""||value=="null"||value=="NULL"){
		result=0;
	}else if(value.indexOf('_')!=-1){
		result = value.split("_")[0];
	}else {
		result = value;
	}

	if(result===null||result==null||result==""||result=="null"||result=="NULL"){
		result=0;
	}
	return result;
}

//申请退回取消事件
function cancel(){
	$('#fmAdd').form('clear');
    $('#dialogAdd').dialog('close');
}

function cancelAudit(){
	$('#dialogAudit').dialog('close');
}

//初始化申请退回弹出窗
function InitForm() {
    var width =280;
    var height = window.screen.height;
    if (height > 160) {
        height = 160;
    }
    $('#dialogAdd').dialog({
        closed: true,
        title: "申请修改",
        width: width,
        height: height
    });
    $('#dialogAudit').dialog({
        closed: true,
        title: "必要性审核",
        width: 400,
        height: 'auto'
    });
    $('#dialogSubmitDiv').dialog({
        closed: true,
        title: "提示",
        width: 400,
        height: 100
    });
}

//前端导出excel
function exportexcel() {
    var grid = $("#tt");
    var rows=grid.datagrid("getRows");					  //获得表格行数据
    var name='数据上报'
    var colums_all=grid.datagrid("options").columns;      		     //获得表格的所有列不包括冻结列
    var obj = $.ExportExcelDlg({
        HeadInfo: colums_all,    //表头栏
        RowInfo: rows,		   //数据航
        FooterInfo: grid.datagrid("getFooterRows"),
        RowStart: 2,		   //导出行位置
        ColumStart: 2,		   //导出列位置
        SheetName: name,
        MainTitle: { Displayname: name, Alignment: 'Center' },
        SaveName: name,
        Swf: 'ExportExcel.swf'
    });
    obj.ExportExcelDlg('open');
}

//各容器自适应
window.onresize = function () {
    var iHeight = document.documentElement.clientHeight;
    $("#tt").datagrid('resize',{height:iHeight-185+'px'});
}

/**
 * 1, "数值"【默认类型，默认返回0】
 * 2, "空格"
 * 3, "暂无数据"
 * 4, "时间"
 * 5, "市级免报"
 * 6, "县级免报"
 */
function getShowValue(rtype, value) {

	if(rtype==2){
		return  "空格";
	}else if(rtype==3){
		return "暂无数据";
	}else if(rtype==4){
		/**带有编辑字符串 <a href='javascript:void(0);' ondblClick='editrow("+ index +")'>" +value +"</a> */
		if(isContains(value, "editrow")){
			var tempvalue=value.substring(value.indexOf(">")+1, value.indexOf("</"));
			var hour=parseInt(tempvalue / 60);
			var minute=tempvalue % 60;
			return hour+":"+minute;
			/** 带有符号的字符串，例如【11:12】 */
		}else if(isContains(value, "：") || isContains(value, ":")){
			return value;
		}else{
			var hour=parseInt(value / 60);
			var minute=value % 60;
			return hour+":"+minute;
		}
	}else if(rtype==5){
		return "市级免报";
	}else if(rtype==6){
		return "县级免报";
	}else if(isEmpty(value)) {
		return "";
	}
	return value;
}

/**
 * 1, "数值"
 * 2, "空格"
 * 3, "暂无数据"
 * 4, "时间"
 * 5, "市级免报"
 * 6, "县级免报"
 */
function getReportValue(rtype, value) {
    if(rtype==1){
        return value;
    } else if(rtype==2||rtype==3||rtype==5||rtype==6){
        return null;
    } else if(rtype==4){
		if(isNumber(value)){
			return value;
		}
        var timeArray=null;
        if(isContains(value, ":")){
            timeArray = value.split(":");
        }else if(isContains(value, "：")){
            timeArray = value.split("：");
        }
        if(timeArray!=null){
			return parseInt(timeArray[0])*60 + parseInt(timeArray[1]);
		} else {
        	return ;
		}
    }
    return null;
}

/**
 * 1, "数值"
 * 2, "空格"
 * 3, "暂无数据"
 * 4, "时间"
 * 5, "市级免报"
 * 6, "县级免报"
 */
function checkValue(rtype, value) {

    if(rtype==1 && isNumber(value)){
        return true;
    }
    if((rtype==2||rtype==3||rtype==5||rtype==6) && (value=='undefined'||value==null||value==0)){
        return true;
    }
    if(rtype==4){
        var timeArray=null;
        if(isContains(value, ":")){
            timeArray = value.split(":");
        }else if(isContains(value, "：")){
            timeArray = value.split("：");
        }
        if(timeArray==null
            ||timeArray.length!=2
            ||!isNumber(timeArray[0])
            ||!isNumber(timeArray[1])){
            return false;
        }
        return true;
    }
    return false;
}

function isContains(str, substr) {
    if(str==null||str=='undefined'){
        return false;
    }
    return str.toString().indexOf(substr) >= 0;
}

function loadForm(){
	$('#formid').combobox({
		onLoadSuccess: function () {
			loadIndicatorType();
		},
		onSelect: function(index, row){
			loadIndicatorType();
		}
	});
}

//获取领域数据
var action_indicator_type_self="/indicator/type/self.do";
function loadIndicatorType() {

	var yearSelect =  $("#yearSelect").combobox("getValue");
	var formsid=$('#formid').combobox('getValue');
	$.get(action_indicator_type_self, {'formsid':formsid, 'year':yearSelect}, function(json) {
		// json.data.unshift({
		//     id : -1,
		//     name : "全部"
		// });
		$('#indicatorTypeSelect').combobox({
			async : false,
			method : 'GET',
			data : json.data,
			valueField : 'id',
			textField : 'name',
			fitColumns:false,
			collapsible: true,
			singleSelect : false,// 是否单选
			checkOnSelect: true,//选中行后,checkbox选中
			selectOnCheck: true,//选中行后,checkbox选中
			// columns: [
			//     defineTableIndicatorTypeNames
			// ],
			multiple:true,
			editable:false,
			formatter:function(row){
				var opts;
				if(row.selected==true){
					opts = "<input type='checkbox' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
				}else{
					opts = "<input type='checkbox' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
				}
				return opts;
			},
			onLoadSuccess : function() { // 数据加载完毕事件
				var a = $('#indicatorTypeSelect').combobox('getData');
				if (a.length > 0) {
					$("#indicatorTypeSelect").combobox('select', a[0].id);
				}
			},
			//二级联动，根据领域获取相应指标数据
			onSelect:function(rec) {
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=true;
				// queryByIndicatorType();
			},
			onUnselect:function(rec){
				oCheckbox = document.getElementById(rec.id);
				oCheckbox.checked=false;
				// queryByIndicatorType();
			},
			onSelectAll: function(index, row){
				// queryByIndicatorType();
			},
			onUnselectAll: function(index, row){
				// queryByIndicatorType();
			}
		});
	}, "json");
}